#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>

#include "render.h"
#include "texture.h"

#include "view.h"
#include "button.h"
#include "layout.h"
#include "resource.h"
#include "animation.h"
#include "template.h"

#include "file.h"
#include "image.h"
#include "system.h"
#include "timer.h"
#include "xml.h"

xmlNodePtr g_xmlAppNode = 0; 

void ufoSetupAppInfo(UFOAPP_INFO *info)
{
	xmlDocPtr doc = 0;			

	char path[300] = {0};
	strcpy(path, ufoGetResPath());
	strcat(path, "app.xml");

	doc = ufoXmlDocFromFile(path);
	
	if (!doc) {
		ufoLog("loading app.xml", "loading app.xml fail");
		return;
	}
	else {
		ufoLog("loading app.xml", "loading app.xml success!");
	}

	g_xmlAppNode = xmlDocGetRootElement(doc);

	if (!g_xmlAppNode || xmlStrcmp(g_xmlAppNode->name, (const xmlChar*)"UFO") != 0) {
		return;
	}

	g_xmlAppNode = g_xmlAppNode->children;

	while (g_xmlAppNode) {//### seek to Resource
		if (xmlStrcmp(g_xmlAppNode->name, (const xmlChar*)"App") == 0) {
			xmlChar *width = xmlGetProp(g_xmlAppNode, (const xmlChar*)"width");
			xmlChar *height = xmlGetProp(g_xmlAppNode, (const xmlChar*)"height");
			xmlChar *style = xmlGetProp(g_xmlAppNode, (const xmlChar*)"style");

			if (width) {
				sscanf(width, "%d", &info->width);
				xmlFree(width);
			}

			if (height) {
				sscanf(height, "%d", &info->height);
				xmlFree(height);
			}

			if (style) {
				if (strcmp(style, "TRANSPARENTS") == 0) {
					info->winStyle = LAYERED_WIN;
				}
				else if (strcmp(style, "STANDARD") == 0) {
					info->winStyle = STANDARD_WIN;
				}
				else if (strcmp(style, "POPUP") == 0) {
					info->winStyle = POPUP_WIN;
				}
				xmlFree(style);
			}

			g_xmlAppNode = g_xmlAppNode->children;
			break;
		}
		g_xmlAppNode = g_xmlAppNode->next;
	}
}

void ufoInitialization()
{
	while (g_xmlAppNode) {
		if (xmlStrcmp(g_xmlAppNode->name, (const xmlChar*)"Resource") == 0) {

			xmlChar *file = xmlGetProp(g_xmlAppNode, (const xmlChar*)"file");

			if (file) {
				char path[300] = {0};
				strcpy(path, ufoGetResPath());
				strcat(path, file);
				ufoResourceAddFromXML(path);
				xmlFree(file);
			}
		}
		else if (xmlStrcmp(g_xmlAppNode->name, (const xmlChar*)"MainView") == 0) {

			xmlChar *file = xmlGetProp(g_xmlAppNode, (const xmlChar*)"file");

			if (file) {
				char path[300] = {0};
				strcpy(path, ufoGetResPath());
				strcat(path, file);
				ufoViewCreateFromXML(0, path);
				xmlFree(file);
			}
		}
		g_xmlAppNode = g_xmlAppNode->next;
	}
}

void ufoUnitialization()
{

}